package com.hzhr.iot.collect.util;

import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class StrUtil {
	public static void main(String[] args) {
		String generateEncryptedMessage = "010101000000810126000000142210182E0000000101000300160818200000100003200000001708182000001500023000000018081820000015000240000000";
		System.out.println(generateEncryptedMessage.length());
		int sum = 0;//校验和
		for (int i = 0; i < generateEncryptedMessage.length(); i += 2) {
			sum += new Integer(StrUtil.hexStr2decStr(generateEncryptedMessage.substring(i, i + 2)));
		}
		String sumStr = Integer.toHexString(sum);
		String encryptedByte = StrUtil.getLowerByte(sumStr);//取低八位
		System.out.println(encryptedByte);

		String a = "68 25 00 10 17 00 00 00 00 26 07 00 22 32 18 10 23 10 00 00 00 0B 00 26 07 00 22 32 11 50 3C 00 00 00 55 D3 16";
		System.out.println(a.replace(" ", ""));

		//System.out.println(removeHexZeroForLeft("0000"));
	}

	public static String obj2str(Object object) {
		if (object == null) return null;
		return object.toString();
	}

	public static List<Integer> str2integerList(String str) {
		if (StringUtils.isEmpty(str)) return null;

		List<Integer> result = new ArrayList<>();
		String[] strSplit = str.split(",");
		for (String strSplitItem:strSplit) {
			result.add(Integer.parseInt(strSplitItem.trim()));
		}
		return result;
	}

	/**
	 * hex字符串转十进制字符串
	 */
	public static String hexStr2decStr(String hex) {
		for (int i = 0; i < hex.length(); i++) {//校验
			char item = hex.charAt(i);
			if (item < '0' || (item > '9' && item < 'A') || (item > 'F' && item < 'a') || item > 'f') return null;
		}

		String result = new BigInteger(hex, 16).toString(10);
		return result;
	}

	/**
	 * 有符号hex字符串转十进制字符串
	 */
	public static String signedHexStr2decStr(String hex) {
		for (int i = 0; i < hex.length(); i++) {//校验
			char item = hex.charAt(i);
			if (item < '0' || (item > '9' && item < 'A') || (item > 'F' && item < 'a') || item > 'f') return null;
		}

		char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5',
				'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
		String firstChar = hex.substring(0, 1);
		int firstCharInt = Integer.parseInt(firstChar, 16);
		if (firstCharInt <= 7) {//正数
			return Integer.parseInt(hex, 16) + "";
		} else {//负数
			firstChar = (firstCharInt - 8) + "";
			String hexTmp = firstChar + hex.substring(1);
			String hexTmpFan = "";
			for (int i = 0; i < hexTmp.length(); i++) {
				char hexTmpChar = hexTmp.charAt(i);
				int dec = Integer.parseInt(hexTmpChar + "", 16);
				if (i == 0) {
					int decFan = 7 - dec;
					hexTmpFan += HEX_CHAR[decFan] + "";
				} else {
					int decFan = 15 - dec;
					hexTmpFan += HEX_CHAR[decFan] + "";
				}

			}
			String result = "-" + (Integer.parseInt(hexTmpFan, 16) + 1);
			return result;
		}

	}

	/**
	 * 字符串转hex字符串
	 */
	public static String str2hexStr(String str) {
		String result = Long.toHexString(Long.parseLong(str));
		int resultLength = result.length();
		if (resultLength % 2 == 1) {//左补零
			result = "0" + result;
		}
		return result;
	}
	
	
	/**
	 * bcd字符串转十进制字符串
	 */
	public static String bcd2decStr(String bcd) {
		for (int i = 0; i < bcd.length(); i++) {//校验
			char item = bcd.charAt(i);
			if (item < '0' || item > '9') return null;
		}

		String result = bcd;
		return result;
	}
	
	/**
	 * 字符串转bcd字符串
	 */
	public static String str2bcdStr(String str) {
		return str;
	}
	
	
	/**
	 * char字符串转字符串
	 */
	public static String char2str(String c) {
		for (int i = 0; i < c.length(); i++) {//校验
			char item = c.charAt(i);
			if (item < '0' || (item > '9' && item < 'A') || (item > 'Z' && item < 'a') || item > 'z') return null;
		}

		byte[] bs = hexStr2byte(c);
		char[] buf = new char[bs.length];
		int index = 0;
		for (byte b : bs) {
			buf[index++] = (char)b;
		}
		return new String(buf);
	}
	


	/**
	 * 把16进制字符串转换成字节数组
	 * 
	 * @param hex
	 * @return byte[]
	 */
	public static byte[] hexStr2byte(String hex) {
		hex = hex.toUpperCase();
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] achar = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
		}
		return result;
	}
	
	
	
	public static String byte2hexStr(byte[] bs) {
		char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', 
	            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
		char[] buf = new char[bs.length * 2];
    	
    	int a = 0;
        int index = 0;
        for(byte b : bs) { // 使用除与取余进行转换
        	//logger.info("binaryData " + b);
            if(b < 0) {
                a = 256 + b;
            } else {
                a = b;
            }

            buf[index++] = HEX_CHAR[a / 16];
            buf[index++] = HEX_CHAR[a % 16];
        }
        
        return new String(buf);
	}

	

	/**
	 * 通过字符串长度截断字符串
	 */
	public static String substringBySize(String str, int beginIndex, int size) {
		if (beginIndex + size > str.length()) return null;
		String result = str.substring(beginIndex, beginIndex + size);
		return result;
	}

	/**
	 * 截断字符串
	 */
	public static String substring(String str, int beginIndex) {
		if (beginIndex > str.length()) return null;
		String result = str.substring(beginIndex, str.length());
		return result;
	}
	public static String substring(String str, int beginIndex, int endIndex) {
		if (beginIndex > str.length() || endIndex > str.length()) return null;
		String result = str.substring(beginIndex, endIndex);
		return result;
	}

	/**
	 * 字符串左补0
	 * 
	 * @param str
	 *            原始字符串
	 * @param size
	 *            补充0之后的长度
	 */
	public static String FillZeroForLeft(String str, int size) {
		if (str == null) return null;
		int strSize = str.length();
		if (strSize < size) {
			int zeroCount = size - strSize;
			for (int i = 0; i < zeroCount; i++) {
				str = "0" + str;
			}
		}
		return str;
	}
	
	/**
	 * 字符串左补0
	 * 
	 * @param str
	 *            原始字符串
	 * @param size
	 *            补充0之后的长度
	 */
	public static String FillZeroForRight(String str, int size) {
		if (str == null) return null;
		int strSize = str.length();
		if (strSize < size) {
			int zeroCount = size - strSize;
			for (int i = 0; i < zeroCount; i++) {
				str = str + "0";
			}
		}
		return str;
	}

	/**
	 * 首字母大写
	 */
	public static String firstCharToUppserCase(String str) {
		StringBuilder sb = new StringBuilder();
		char[] cs = str.toCharArray();

		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			if (i == 0) {
				sb.append(Character.toUpperCase(c));
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}

	/**
	 * 首字母小写
	 */
	public static String firstCharToLowerCase(String str) {
		StringBuilder sb = new StringBuilder();
		char[] cs = str.toCharArray();

		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			if (i == 0) {
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}

	/**
	 * 字符串转小写
	 * 
	 * @title strToLowerCase
	 * @description
	 * @param str
	 * @return
	 * @author 48310
	 * @date 2018年4月10日
	 * @see
	 *
	 */
	public static String strToLowerCase(String str) {
		StringBuilder sb = new StringBuilder();
		char[] cs = str.toCharArray();

		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			if (Character.isUpperCase(c)) {
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}

		return sb.toString();
	}

	/**
	 * 进行crc校验，返回校验结果
	 */
	public static String getCrc16(byte[] targetBs) { 
        int CRC = 0x0000ffff;  
        int POLYNOMIAL = 0x0000a001;  
        int i, j;  
  
        byte[] resultBs = new byte[targetBs.length];
        for (i = 0; i < targetBs.length; i++)  
        {  
            CRC ^= ((int)targetBs[i] & 0x000000ff);  
            for (j = 0; j < 8; j++)  
            {  
                if ((CRC & 0x00000001) != 0)  
                {  
                    CRC >>= 1;  
                    CRC ^= POLYNOMIAL;  
                }  
                else  
                {  
                    CRC >>= 1;  
                }  
            }  
            //System.out.println(Integer.toHexString(CRC));   
        }  
          
        resultBs[0] = (byte)(CRC & 0x00ff);  
        resultBs[1] = (byte)(CRC >> 8);  
  
        String crcStr = byte2hexStr(resultBs).substring(0, 4);
        crcStr = reverseUpperAndLowerByte(crcStr);//高低位取反(兼容硬件)
        return crcStr;
	}
	
	/**
	 * 获取低字节
	 */
	public static String getLowerByte(String byteStr) {
		if (byteStr.length() > 2) {
			byteStr = byteStr.substring(byteStr.length() - 2, byteStr.length());
		} else if (byteStr.length() < 2) {
			byteStr = FillZeroForLeft(byteStr, 2);
		}
		return byteStr;
	} 
	
	/**
	 * 反转高低字节
	 * @param byteStr 字节字符串
	 * @return
	 */
	public static String reverseUpperAndLowerByte(String byteStr) {
		StringBuilder resultSb = new StringBuilder();
		for (int i = byteStr.length() - 2; i >= 0; i -= 2) {
			resultSb.append(byteStr.charAt(i) + "" + byteStr.charAt(i + 1));
		}
		return resultSb.toString();
	}
	
	public static List<String> listStr2list(String listStr) {
		if (listStr.startsWith("[") && listStr.endsWith("]")) {
			listStr = listStr.substring(1, listStr.length() - 1);
			String[] strs = listStr.split(",");
			List<String> list = new ArrayList<>();
			for (String str : strs) {
				list.add(str);
			}
			return list;
		} else {
			List<String> result = new ArrayList<>();
			result.add(listStr);
			return result;
		}

	}
	
	public static String replaceLast(String text, String regex, String replacement) {
        return text.replaceFirst("(?s)"+regex+"(?!.*?"+regex+")", replacement);
    }

	/**
	 * 字符串左去0
	 * @param str 原始字符串
	 */
	public static String removeZeroForLeft(String str) {
		int strSize =  str.length();
		String result = "";
		for (int i = 0; i < strSize; i++) {
			char c = str.charAt(i);
			if (c != '0') {
				result += str.substring(i);
				break;
			}
		}
		return result;
	}

	/**
	 *  HEX字符串左去0
	 * @param str 原始字符串
	 */
	public static String removeHexZeroForLeft(String str) {
		if (str == null) return str;
		if (str.replace("0", "").equals("")) return str;//如果全0则不做处理

		int strSize =  str.length();
		String result = "";
		for (int i = 0; i < strSize; i += 2) {
			String hex = str.substring(i, i + 2);
			if (!"00".equals(hex)) {
				result += str.substring(i);
				break;
			}
		}
		return result;
	}
	
	private static int toByte(char c) {
		byte b = (byte) "0123456789ABCDEF".indexOf(c);
		return b;
	}

	public static String decimal2binary(int n) {
		int t = 0;  //用来记录位数
		long bin = 0; //用来记录最后的二进制数
		int r = 0;  //用来存储余数
		while(n != 0){
			r = n % 2;
			n = n / 2;
			bin += r * Math.pow(10,t);
			t++;
		}

		String result = bin + "";
		if (result.length() % 2 != 0) {//如果位数为奇数，需要补充为偶数位
			result = "0" + result;
		}
		return result;
	}
}
